// @author: caoshi
// @date: 2021-06-06 09:53
// 生成验证码工具类

package captcha

import (
	"github.com/mojocn/base64Captcha"
)

const SourceStr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

// 验证码类型"枚举"
type ChaptchaType string

const (
	String  ChaptchaType = "string"  // 简单字符串
	Math    ChaptchaType = "math"    // 数学计算式子
	Chiness ChaptchaType = "chiness" // 字母数字随机组合
)

// 图片宽高, 以前端页面为准
const (
	Width  int = 100
	Height int = 40
)

// 验证码对象的基本配置
type captchaConfig struct {
	Id            string
	ChaptchaType  ChaptchaType // 验证码类型
	VerifyValue   string
	DriverAudio   *base64Captcha.DriverAudio
	DriverString  *base64Captcha.DriverString
	DriverChinese *base64Captcha.DriverChinese
	DriverMath    *base64Captcha.DriverMath
	DriverDigit   *base64Captcha.DriverDigit
}

// 生成验证码, 可选类型
func GenerateCaptcha(cType ChaptchaType) (id string, b64s string, err error) {
	config := captchaConfig{
		Id:           "",
		ChaptchaType: cType,
		DriverDigit: &base64Captcha.DriverDigit{
			Height:   Height,
			Width:    Width,
			Length:   4,
			MaxSkew:  0.7,
			DotCount: 8,
		},
		DriverChinese: &base64Captcha.DriverChinese{
			Height:          Height,
			Width:           Width,
			NoiseCount:      10,
			ShowLineOptions: 1,
			Length:          4,
			Source:          SourceStr,
			BgColor:         nil,
			Fonts:           nil,
		},
		DriverMath: &base64Captcha.DriverMath{
			Height:          Height,
			Width:           Width,
			NoiseCount:      10,
			ShowLineOptions: 1,
			BgColor:         nil,
			Fonts:           nil,
		},
		DriverString: &base64Captcha.DriverString{
			Height:          Height,
			Width:           Width,
			NoiseCount:      10,
			ShowLineOptions: 1,
			Length:          4,
			Source:          SourceStr,
			BgColor:         nil,
			Fonts:           nil,
		},
	}

	var driver base64Captcha.Driver

	switch config.ChaptchaType {
	case String:
		driver = config.DriverString.ConvertFonts()
	case Math:
		driver = config.DriverMath.ConvertFonts()
	case Chiness:
		driver = config.DriverChinese.ConvertFonts()
	default:
		driver = config.DriverDigit
	}

	// 默认字符串验证码
	captcha := base64Captcha.NewCaptcha(driver, base64Captcha.DefaultMemStore)
	id, str, err := captcha.Generate()
	return id, str, err
}

// 校验
func VerifyCaptcha(capychaId, verifyValue string) bool {
	pass := base64Captcha.DefaultMemStore.Verify(capychaId, verifyValue, true)
	return pass
}
